package com.julis.activity.main.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.Constant;
import com.baseutils.SpfUtils;
import com.bigkoo.pickerview.TimePickerView;
import com.excel.ExcelUtils;
import com.github.czy1121.view.RoundButton;
import com.julis.R;
import com.julis.activity.record.adapter.MyRVAdapter;
import com.julis.activity.setting.Setting2_Activity;
import com.julis.activity.setting.Setting_Activity;
import com.julis.bean.Obu_Info;
import com.julis.db.Z_ObuInfoDao;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 检测记录
 */
public class Record_Fragment extends Fragment {
    View view;
    MyRVAdapter mAdapter;
    Z_ObuInfoDao z_obuInfoDao;
    List<Obu_Info> obu_infos = new ArrayList<>();
    @BindView(R.id.recyclerView)
    RecyclerView mRvMain;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;
    @BindView(R.id.bt_daochu)
    RoundButton btDaochu;


    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_startvalue)
    TextView tvStartvalue;
    @BindView(R.id.layout_start)
    RelativeLayout layoutStart;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.tv_endvalue)
    TextView tvEndvalue;
    @BindView(R.id.layout_end)
    RelativeLayout layoutEnd;
    @BindView(R.id.bt_chaxun)
    RoundButton btChaxun;
    @BindView(R.id.ed_vinvalue)
    EditText ed_vinvalue;
    @BindView(R.id.spinner_blood_pressure)
    Spinner spinnerBloodPressure;
    @BindView(R.id.layout_riqi)
    LinearLayout layoutRiqi;
    @BindView(R.id.tv_vin)
    TextView tvVin;
    @BindView(R.id.layout_vin)
    RelativeLayout layoutVin;
    @BindView(R.id.tv_obumac)
    TextView tvObumac;
    @BindView(R.id.ed_obumacvalue)
    EditText edObumacvalue;
    @BindView(R.id.layout_obumac)
    RelativeLayout layoutObumac;
    @BindView(R.id.layout_daochu)
    RelativeLayout layout_daochu;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = View.inflate(getActivity(), R.layout.fragment_record, null);
            ButterKnife.bind(this, view);
            z_obuInfoDao = new Z_ObuInfoDao(getActivity());
            initview();
            init();
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        obu_infos.clear();
        mAdapter.clear();
        mAdapter.notifyDataSetChanged();
    }

    List<String> ccList = new ArrayList<String>();
    ArrayAdapter spinnerAdapter;
    int querytype = 1;

    public void init() {
        String name = (String) SpfUtils.get(getActivity(), "name", "");
        if (!name.equals("admin")) {
            layout_daochu.setVisibility(View.GONE);
        } else {
            layout_daochu.setVisibility(View.VISIBLE);
        }
        ccList.add("日期查询");
        ccList.add("VIN号查询");
        ccList.add("MAC号查询");
        spinnerAdapter = new ArrayAdapter<String>(getActivity(),
                R.layout.item_select, ccList);
        spinnerAdapter.setDropDownViewResource(R.layout.item_drop);
        spinnerBloodPressure.setAdapter(spinnerAdapter);
        spinnerBloodPressure.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                String name = ccList.get(pos);
                if (name.equals("日期查询")) {
                    layoutVin.setVisibility(View.GONE);
                    layoutRiqi.setVisibility(View.VISIBLE);
                    layoutObumac.setVisibility(View.GONE);
                    querytype = 1;
                    obu_infos.clear();
                    mAdapter.clear();
                    mAdapter.notifyDataSetChanged();
                } else if (name.equals("VIN号查询")) {
                    layoutVin.setVisibility(View.VISIBLE);
                    ed_vinvalue.setText("");
                    layoutRiqi.setVisibility(View.GONE);
                    layoutObumac.setVisibility(View.GONE);
                    querytype = 2;
                    obu_infos.clear();
                    mAdapter.clear();
                    mAdapter.notifyDataSetChanged();
                } else if (name.equals("MAC号查询")) {
                    edObumacvalue.setText("");
                    layoutVin.setVisibility(View.GONE);
                    layoutRiqi.setVisibility(View.GONE);
                    layoutObumac.setVisibility(View.VISIBLE);
                    querytype = 3;
                    obu_infos.clear();
                    mAdapter.clear();
                    mAdapter.notifyDataSetChanged();
                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        // 设置布局
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mRvMain.setLayoutManager(linearLayoutManager);
        mRvMain.addItemDecoration(
                new HorizontalDividerItemDecoration.Builder(getActivity()).build());
        mAdapter = new MyRVAdapter(getActivity());
        mRvMain.setAdapter(mAdapter);
//        shuaxin();
        mAdapter.setOnItemClickListener(new MyRVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                Toast.makeText(UIUtil.getContext(), "click" + position, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position) {
//                Toast.makeText(UIUtil.getContext(), "long click" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void shuaxin() {
        mAdapter.clear();
        obu_infos = z_obuInfoDao.queryForAll();
        Collections.reverse(obu_infos);
        mAdapter.addItem(obu_infos);
    }

    private String fileName;
    private ArrayList<ArrayList<String>> recordList;

    File file;
    private static String[] title = {"编号", "vin号", "obu编号", "Vin录入",
            "obu录入", "OBU自检", "蓝牙检测", "vin写入", "obu交易", "检测时间"};

    /**
     * 导出excel
     *
     * @param
     */
    public void out_excel() {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH_mm_ss");
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        file = new File(getSDPath() + "/Record");
        makeDir(file);
        updata(getActivity(), file);
        ExcelUtils.initExcel(file.toString() + "/流水线检测" + str + ".xls", title, getActivity());
        fileName = getSDPath() + "/Record/流水线检测" + str + ".xls";
        ExcelUtils.writeObjListToExcel(getRecordData(), fileName, getActivity());
    }

    public static void updata(Context context, File file) {
        MediaScannerConnection.scanFile(context,
                new String[]{file.getAbsolutePath()}, null, null);
    }

    /**
     * 将数据集合 转化成ArrayList<ArrayList<String>>
     *
     * @return
     */
    private ArrayList<ArrayList<String>> getRecordData() {

        recordList = new ArrayList<>();
        for (int i = 0; i < obu_infos.size(); i++) {
            Obu_Info obuTradeInfo = obu_infos.get(i);
            ArrayList<String> beanList = new ArrayList<String>();
            beanList.add("" + (i + 1));
            beanList.add(obuTradeInfo.getVincode());
            beanList.add(obuTradeInfo.getObu_code());
            if (!TextUtils.isEmpty(obuTradeInfo.getVin_input_success())) {
                beanList.add(obuTradeInfo.getVin_input_success().equals("true") ? "成功" : "失败");
            } else {
                beanList.add(obuTradeInfo.getVin_input_success());
            }
            if (!TextUtils.isEmpty(obuTradeInfo.getObu_input_success())) {
                beanList.add(obuTradeInfo.getObu_input_success().equals("true") ? "成功" : "失败");
            } else {
                beanList.add(obuTradeInfo.getObu_input_success());
            }
            if (!TextUtils.isEmpty(obuTradeInfo.getKl15_success())) {
                beanList.add(obuTradeInfo.getKl15_success().equals("true") ? "成功" : "失败");
            } else {
                beanList.add(obuTradeInfo.getKl15_success());
            }


            if (!TextUtils.isEmpty(obuTradeInfo.getBle_check_success())) {
                beanList.add(obuTradeInfo.getBle_check_success().equals("true") ? "成功" : "失败");
            } else {
                beanList.add(obuTradeInfo.getBle_check_success());
            }
            if (!TextUtils.isEmpty(obuTradeInfo.getVin_write_success())) {
                beanList.add(obuTradeInfo.getVin_write_success().equals("true") ? "成功" : "失败");
            } else {
                beanList.add(obuTradeInfo.getVin_write_success());
            }
            if (!TextUtils.isEmpty(obuTradeInfo.getObu_check_success())) {
                StringBuilder sb = new StringBuilder("");
                sb.setLength(0);
                String obu_check_success = obuTradeInfo.getObu_check_success().substring(1, obuTradeInfo.getObu_check_success().length() - 1);
                String[] arr = obu_check_success.split(","); // 用,分割
                for (int z = 0; z < arr.length; z++) {
                    String s = arr[z];
                    String   data= Constant.ManufacturerName;
                    sb.append("OBU"+data+"第" + (z + 1) + "次：" + s.substring(1, s.length() - 1));
                    if (z < arr.length) {
                        sb.append(";");
                    }

                }

                beanList.add(sb.toString());


            }
            if (!TextUtils.isEmpty(obuTradeInfo.getDevice_check_device_check_time())) {
                beanList.add(obuTradeInfo.getDevice_check_device_check_time());
            } else {
                beanList.add(obuTradeInfo.getDevice_check_device_check_time());
            }

            recordList.add(beanList);
        }
        return recordList;
    }

    private String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        String dir = sdDir.toString();
        return dir;
    }

    public void makeDir(File dir) {
        if (!dir.getParentFile().exists()) {
            makeDir(dir.getParentFile());
        }
        dir.mkdir();
    }


    @OnClick({  R.id.bt_daochu, R.id.bt_chaxun, R.id.layout_start, R.id.layout_end})
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.setting:
//                String name = (String) SpfUtils.get(getActivity(), "name", "");
//                if (!name.equals("admin")) {
//                    startActivity(new Intent(getActivity(), Setting2_Activity.class));
//                } else {
//                    startActivity(new Intent(getActivity(), Setting_Activity.class));
//                }

//                break;
            case R.id.bt_chaxun:
                obu_infos.clear();
                if (querytype == 1) {
                    //日期查询
                    if (TextUtils.isEmpty(tvStartvalues)) {
                        Toast.makeText(getActivity(), "请选择开始时间", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (TextUtils.isEmpty(tvendvalues)) {
                        Toast.makeText(getActivity(), "请选择结束时间", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    obu_infos = z_obuInfoDao.query(tvStartvalues, tvendvalues);

                } else if (querytype == 2) {
                    //Vin号查询
                    String vinvalue = ed_vinvalue.getText().toString();
                    if (TextUtils.isEmpty(vinvalue)) {
                        Toast.makeText(getActivity(), "请输入VIN号", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    obu_infos = z_obuInfoDao.queryvin(vinvalue);

                } else if (querytype == 3) {
                    //MAC号查询
                    String Obumacvalue = edObumacvalue.getText().toString();
                    if (TextUtils.isEmpty(Obumacvalue)) {
                        Toast.makeText(getActivity(), "请输入OBU MAC号", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    obu_infos = z_obuInfoDao.querymac(Obumacvalue);


                }

                if (obu_infos != null && obu_infos.size() > 0) {
                    Collections.reverse(obu_infos);
                    mAdapter.clear();
                    mAdapter.addItem(obu_infos);
                    Toast.makeText(getActivity(), "查询成功！", Toast.LENGTH_SHORT).show();
                } else {
                    mAdapter.clear();
                    mAdapter.addItem(obu_infos);
                    Toast.makeText(getActivity(), "暂无数据！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.bt_daochu:
                if (obu_infos != null && obu_infos.size() > 0) {
                    mAdapter.clear();
                    mAdapter.addItem(obu_infos);
                    out_excel();
                    Toast.makeText(getActivity(), "导出成功！", Toast.LENGTH_SHORT).show();
                } else {
                    mAdapter.clear();
                    mAdapter.addItem(obu_infos);
                    Toast.makeText(getActivity(), "暂无数据！", Toast.LENGTH_SHORT).show();
                }


                break;
            case R.id.layout_start:
                type = "1";
                pvTime.show(tvStart);

                break;
            case R.id.layout_end:
                type = "2";
                pvTime.show(tvStart);

                break;
        }
    }


    TimePickerView pvTime;
    List<Obu_Info> obu_infos2;
    String tvStartvalues = "";
    String tvendvalues = "";

    void initview() {

        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2013, 0, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2029, 11, 28);
        tvStartvalue.setText(getTimes(new Date()));
        tvEndvalue.setText(getTimes(new Date()));
        tvStartvalues = getTimes(new Date());
        tvendvalues = getTimes(new Date());
        //时间选择器
        pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                String times = getTimes(date);
                Log.e("ZZZ", "xx" + times);
                if (type.equals("1")) {
                    tvStartvalue.setText(times);
                    tvStartvalues = times;
                } else {
                    tvEndvalue.setText(times);
                    tvendvalues = times;
                }

            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "时", "", "")
                .isCenterLabel(true)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .build();
    }

    String type = "1";

    private String getTimes(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public static int compare_date(String DATE1, String DATE2) {


        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }


}
